package cn.com.openportal.ffw.modules.sys.controller;

import cn.com.openportal.ffw.common.annotation.SysLog;
import cn.com.openportal.ffw.common.exception.RRException;
import cn.com.openportal.ffw.common.utils.Constant;
import cn.com.openportal.ffw.common.utils.R;
import cn.com.openportal.ffw.modules.sys.entity.SysDeptEntity;
import cn.com.openportal.ffw.modules.sys.service.SysDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 部门管理
 *
 * @author LeeSon
 */
@RestController
@RequestMapping("/sys/dept")
public class SysDeptController extends AbstractController {
    @Autowired
    private SysDeptService sysDeptService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:dept:list")
    public List<SysDeptEntity> list() {
        List<SysDeptEntity> deptList = sysDeptService.queryList(new HashMap<String, Object>());

        return deptList;
    }

    /**
     * 选择部门(添加、修改菜单)
     */
    @RequestMapping("/select")
    @RequiresPermissions("sys:dept:select")
    public R select() {
        List<SysDeptEntity> deptList = sysDeptService.queryList(new HashMap<String, Object>());

        return R.ok().put("deptList", deptList);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{deptId}")
    @RequiresPermissions("sys:dept:info")
    public R info(@PathVariable("deptId") Long deptId) {

        checkDeptId(deptId, true);

        SysDeptEntity dept = sysDeptService.getById(deptId);

        return R.ok().put("dept", dept);
    }

    /**
     * 保存
     */
    @SysLog("保存部门")
    @RequestMapping("/save")
    @RequiresPermissions("sys:dept:save")
    public R save(@RequestBody SysDeptEntity dept) {

        dept = check(dept, false);

        sysDeptService.save(dept);

        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改部门")
    @RequestMapping("/update")
    @RequiresPermissions("sys:dept:update")
    public R update(@RequestBody SysDeptEntity dept) {

        if (dept.getDeptId().longValue() == checkPrems().longValue()) {
            dept = check(dept, true);
        } else {
            dept = check(dept, false);
        }

        sysDeptService.updateById(dept);

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除部门")
    @PostMapping("/delete/{deptId}")
    @RequiresPermissions("sys:dept:delete")
    public R delete(@PathVariable("deptId") long deptId) {

        checkDeptId(deptId, false);

        //判断是否有子部门
        List<Long> deptList = sysDeptService.queryDetpIdList(deptId);
        if (deptList.size() > 0) {
            return R.error("请先删除子部门");
        }

        SysDeptEntity e = sysDeptService.getById(deptId);
        if (null != e) {
            e.setDelFlag(1);
            sysDeptService.updateById(e);
            //sysDeptService.removeById(deptId);
        }

        return R.ok();
    }

    /**
     * 检查权限
     */
    private Long checkPrems() {
        if (getUserId() != Constant.SUPER_ADMIN) {
            Long currentDeptId = getUser().getDeptId();
            return currentDeptId;
        }
        return null;
    }

    /**
     * 检查DeptId+检查权限
     */
    private List<Long> checkDeptId(Long deptId, boolean isContainCurrentDept) {
        List<Long> deptIds = new ArrayList<>();
        Long currentDeptId = checkPrems();
        if (null != currentDeptId) {
            deptIds = sysDeptService.getSubDeptIdList(currentDeptId);
            if (isContainCurrentDept) {
                deptIds.add(currentDeptId);
            }
            if (null != deptId) {
                boolean permit = false;
                for (long id : deptIds) {
                    if (id == deptId.longValue()) {
                        permit = true;
                        break;
                    }
                }
                if (!permit) {
                    throw new RRException("权限限制");
                }
            }
        }
        return deptIds;
    }

    /**
     * 检查ParentId+检查DeptId+检查权限
     */
    private void checkParentId(List<Long> deptIds, Long parentId, boolean isContainCurrentParentDept) {
        if (null != parentId && null != deptIds) {
            if (isContainCurrentParentDept) {
                deptIds.add(parentId);
            }
            boolean permit = false;
            for (long id : deptIds) {
                if (id == parentId.longValue()) {
                    permit = true;
                    break;
                }
            }
            if (!permit) {
                throw new RRException("权限限制");
            }
        }
    }

    /**
     * 检查权限 树形检查
     */
    private SysDeptEntity check(SysDeptEntity dept, boolean isContainCurrentParentDept) {
        if (null != dept) {
            Long deptId = dept.getDeptId();
            Long parentId = dept.getParentId();
            checkParentId(checkDeptId(deptId, true), parentId, isContainCurrentParentDept);
            if (null != parentId) {
                List<Long> ids = sysDeptService.getSubDeptIdList(deptId);
                if (null != deptId) {
                    ids.add(deptId);
                }
                for (long id : ids) {
                    if (id == parentId.longValue()) {
                        dept.setParentId(null);
                        break;
                    }
                }
            }
        }
        return dept;
    }

}
